package com.vf.admin.client.controller;

import cn.hutool.core.util.ObjectUtil;
import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dao.AppDynamicDao;
import com.vf.admin.client.dto.DynamicDto;
import com.vf.admin.client.service.*;
import com.vf.admin.common.Constants;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.utils.StringEx;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.vf.admin.client.common.ClientConstants.client_toke;
import static com.vf.admin.common.Constants.guizuCacheMap;
import static com.vf.admin.utils.DateJisuan.format;
import static com.vf.admin.utils.StringEx.isNull;

/**
 * 动态控制器
 */
@Controller
@RequestMapping("/app/dynamic")
public class AppDynamicController extends ClientBaseController {

    @Autowired
    AppDynamicDao appDynamicDao;
    @Autowired
    AppUserService appUserService;
    @Autowired
    AppUserDressupService appUserDressupService;
    @Autowired
    AppUserDongtaiService appUserDongtaiService;
    @Autowired
    AppDynamicDianzanService appDynamicDianzanService;
    @Autowired
    AppFollowService appFollowService;
    @Autowired
    private AppDynamicService appDynamicService;
    @Autowired
    private AppCommentService appCommentService;
    @Autowired
    private AppUserSettingService userSettingService;
    @Autowired
    private DynamicAlertService dynamicAlertService;
    @Autowired
    RedisUtil redisUtil;

    @Resource
    private AppSetupService appSetupService;
    /**
     * 获取热门动态
     *
     * @param pageno 第几页
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public Result list(Integer pageno) {

        if (StringEx.isNull(pageno)) {
            return this.errorJSON("Pagination cannot be empty!");
        }
        //判断用户是否登录
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
        //获取当前登录用户的user对象
        AppUser user = appUserService.get(userId);
        Map<String, Object> params = new HashMap<>();
        params.put("sex", this.oppositeSex(user.getSex()));
        params.put("userId", userId);
        //查询 用户  开启不看ta动态按钮  的用户列表
        String arr1 = "";
        List<AppUserDongtai> dongtaiList = appUserDongtaiService.findList(user.getId());
        if (dongtaiList != null && dongtaiList.size() > 0) {
            arr1 = dongtaiList.stream().map(e -> e.getGbuserid().toString()).collect(Collectors.joining(","));
            params.put("excludeUserId", arr1);
        }

        //过滤拉黑朋友圈
        //查询被拉黑的用户
        List<AppUser> ids = appUserService.isBlackList();
        String arr2 = "";
        if (ids != null && ids.size() > 0) {
            arr2 = ids.stream().map(e -> e.getId().toString()).collect(Collectors.joining(","));
            params.put("states",arr2);
        }

        //审查
        AppSetup appSetup = appSetupService.get();
        if (ObjectUtil.isNotEmpty(appSetup)){

            if (appSetup.getAuditStatus().equals(1)){
                String idss = appSetup.getCircleIds();
                params.put("ids",idss);

            }
        }


        //查询动态列表
        SplitPageBean splitPageBean = new SplitPageBean(pageno, 10);
        List<AppDynamic> list = appDynamicDao.applist(params, splitPageBean);

        String dtidArr = "";
        String dtuserArr = "";
        String userArr = "";
        for (AppDynamic dynamic : list) {
            dtidArr += "," + dynamic.getId();
            dtuserArr += "," + dynamic.getUserid();
            userArr += "," + dynamic.getUserid();
        }
        if (!isNull(dtidArr)) {
            dtidArr = dtidArr.substring(1);
        }
        if (!isNull(dtuserArr)) {
            dtuserArr = dtuserArr.substring(1);
        }
        if (!isNull(userArr)) {
            userArr = userArr.substring(1);
        }
        List<DynamicDto> toList = new ArrayList<>();
        //批量查询是否已经点赞
        List<AppDynamicDianzan> dianzanList = appDynamicDianzanService.getPiliang(user.getId(), dtidArr);
        Map<Integer, Integer> dianzanMap = new HashMap<>(16);
        for (AppDynamicDianzan dianzan : dianzanList) {
            dianzanMap.put(dianzan.getDynamicid(), 1);
        }
        //批量查询是否已经关注发布人
        Map<Integer, Integer> followMap = new HashMap<>(16);
        if (!isNull(dtuserArr)) {
            List<AppFollow> followList = appFollowService.getPiliang(user.getId(), dtuserArr);
            for (AppFollow follow : followList) {
                followMap.put(follow.getUserid(), 1);
            }
        }
        //批量查询发布人信息
        Map<Integer, AppUser> userMap = new HashMap<>(16);
        if (!isNull(userArr)) {
            List<AppUser> userList = appUserService.getPiliang(userArr);
            for (AppUser user1 : userList) {
                userMap.put(user1.getId(), user1);
            }
        }
        //批量查询发布人默认头饰
        Map<Integer, Integer> toushiMap = new HashMap<>(16);
        if (!isNull(userArr)) {
            List<AppUserDressup> userDressups = appUserDressupService.getPiliang(userArr, 2);
            for (AppUserDressup userDressup : userDressups) {
                if (userDressup.getState() == 1) {
                    toushiMap.put(userDressup.getUserid(), userDressup.getMountsid());
                }
            }
        }
        for (AppDynamic dynamic : list) {
            DynamicDto dd = new DynamicDto();
            BeanUtils.copyProperties(dynamic, dd);
            if (!isNull(dd.getImage())) { //判断动态图片是否为空
                String[] arr = dd.getImage().split(","); //不为空  切割
                if (arr != null && arr.length > 0) {
                    dd.setImageList(Arrays.asList(arr)); //移入数组
                }
            } else {
                dd.setImageList(Arrays.asList());//为空  数组则为空
            }
            //判断点赞map里是否存在动态信息
            if (dianzanMap.containsKey(dynamic.getId())) {
                //存在则表示已点赞
                dd.setDzstate(1);
            } else {
                //不存在则表示未点赞
                dd.setDzstate(2);
            }
            //判断关注map里是否存在关注信息
            if (followMap.containsKey(dynamic.getUserid())) {
                //存在则表示已点赞
                dd.setGuanzhuState(1);
            } else {
                //不存在则表示未点赞
                dd.setGuanzhuState(2);
            }
            dd.setFabuTime(format(dd.getCreatetime()));
            AppUser user2 = userMap.get(dynamic.getUserid());
//            if (user2.getIsguizu() == 1) {
//                //是贵族
//                //根据贵族id  获取贵族图标
//                String medal = guizuCacheMap.get(user2.getNobleid());
//                dd.setMedal(medal);
//            } else {
//                dd.setMedal("");
//            }
            //判断是否设置过头饰
            if (toushiMap.containsKey(dynamic.getUserid())) {
                //存在则放入
                dd.setToushi(Constants.toushiCacheMap.get(toushiMap.get(dynamic.getUserid())));
            } else {
                //不存在则表示未点赞
                dd.setToushi("");
            }
            if (redisUtil.hasKey(RedisKeys.BECKONING + user.getId() + "-" + dynamic.getUserid())) {
                dd.setIsBeckoning(1);
            } else {
                dd.setIsBeckoning(2);
            }

            AppUser appUser = appUserService.get(dynamic.getUserid());
            if (ObjectUtil.isNotEmpty(appUser)){

                dd.setTengxuncode(appUser.getTengxuncode());
            }
            toList.add(dd);
        }
        return this.sucessPage(toList, splitPageBean.getNextPageNo());
    }


    /**
     * 获取附近的朋友圈列表
     *
     * @param splitPageBean
     * @return
     */
    @RequestMapping("/nearbyDynamics")
    @ResponseBody
    public Result nearbyDynamics(SplitPageBean splitPageBean) {
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
        if (userId == null) return errorJSON("请登录");
        ArrayList<DynamicDto> list = new ArrayList<>();

        AppUser user1 = appUserService.get(userId);
        List<AppDynamic> appDynamics = null;
        if (user1.getLon() != null && user1.getLat() != null) {
            Map<String, Object> params = new HashMap<>();
            params.put("lon", user1.getLon());
            params.put("lat", user1.getLat());
            //筛掉隐藏位置信息的用户
            List<Map> userIdsByHiddenArea = userSettingService.getUserIdsByHiddenArea();
            String hiddenUserIds = userIdsByHiddenArea.stream().map(e -> e.get("userId").toString()).collect(Collectors.joining(","));
            if (StringUtils.isNotBlank(hiddenUserIds)) {
                params.put("hiddenUserIds", hiddenUserIds);
            }
            appDynamics = appDynamicService.selectNearbyPage(params, splitPageBean);
        }
        //用户没有位置信息查询所有动态
        if (appDynamics == null || appDynamics.size() == 0) {
            Map<String, Object> params = new HashMap<>();
            params.put("sex", this.oppositeSex(user1.getSex()));
            params.put("userId", userId);
            //查询 用户  开启不看ta动态按钮  的用户列表
            String arr1 = "";
            List<AppUserDongtai> dongtaiList = appUserDongtaiService.findList(userId);
            if (dongtaiList != null && dongtaiList.size() > 0) {
                arr1 = dongtaiList.stream().map(e -> e.getGbuserid().toString()).collect(Collectors.joining(","));
                params.put("excludeUserId", arr1);
            }
            appDynamics = appDynamicDao.applist(params, splitPageBean);
        }
        appDynamics.forEach(e -> {
            //处理图片
            DynamicDto dd = new DynamicDto();
            BeanUtils.copyProperties(e, dd);
            if (!isNull(dd.getImage())) { //判断动态图片是否为空
                String[] arr = dd.getImage().split(","); //不为空  切割
                if (arr != null && arr.length > 0) {
                    dd.setImageList(Arrays.asList(arr)); //移入数组
                }
            } else {
                dd.setImageList(Arrays.asList());//为空  数组则为空
            }
            //是否点赞
            AppDynamicDianzan specifiedLike = appDynamicDianzanService.getSpecifiedLike(dd.getUserid(), dd.getId());
            dd.setDzstate(Objects.isNull(specifiedLike) ? 2 : 1);
            //点赞数量
            dd.setGivenum(appDynamicDianzanService.count(dd.getId()).size());
            //评论数量
            dd.setCommentnum(appCommentService.plcount(dd.getId()));
            //贵族设置
            AppUser user = appUserService.get(dd.getUserid());
            if (user.getIsguizu() == 1) {
                //根据贵族id  获取贵族图标
                String medal = guizuCacheMap.get(user.getNobleid());
                dd.setMedal(medal);
            } else {
                dd.setMedal("");
            }
            //头饰
            AppUserDressup dressup = appUserDressupService.getUserid(dd.getUserid(), 2);
            if (Objects.nonNull(dressup)) {
                //存在则放入
                dd.setToushi(Constants.toushiCacheMap.get(dressup.getMountsid()));
            } else {
                //不存在则表示未点赞
                dd.setToushi("");
            }
            if (redisUtil.hasKey(RedisKeys.BECKONING + user.getId() + "-" + dd.getUserid())) {
                dd.setIsBeckoning(1);
            } else {
                dd.setIsBeckoning(2);
            }
            dd.setTengxuncode(user.getTengxuncode());
            //显示发布时间
            dd.setFabuTime(format(dd.getCreatetime()));
            if (appUserService.isVip(user.getId())) {
                dd.setIsVip(1);
            }
            list.add(dd);
        });
        if (list.size() == 0) {
            return this.sucessJSON(new ArrayList<>(), "成功");
        }
        return this.sucessPage(list, splitPageBean.getNextPageNo());
    }


    /**
     * 获取关注人的朋友圈
     *
     * @param splitPageBean
     * @return
     */
    @RequestMapping("/followList")
    @ResponseBody
    public Result followList(SplitPageBean splitPageBean) {
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
        if (userId == null) return errorJSON("请登录");
        //获取关注人的IDS
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("followeduserid", userId);
        List<AppFollow> byList = appFollowService.findByListAll(hashMap);
        String ids = byList.stream().map(e -> e.getUserid().toString()).collect(Collectors.joining(","));
        if (ids == null || ids.equals("")) return this.sucessJSON(new ArrayList<>(), "成功");
        //获取IDS对应的朋友圈
        HashMap<String, Object> map = new HashMap<>();
        map.put("userIds", ids);


        //过滤拉黑朋友圈
        //查询被拉黑的用户
        List<AppUser> appUsers = appUserService.isBlackList();
        String arr2 = "";
        if (appUsers != null && appUsers.size() > 0) {
            arr2 = appUsers.stream().map(e -> e.getId().toString()).collect(Collectors.joining(","));
            map.put("states",arr2);
        }


        List<AppDynamic> appDynamics = appDynamicService.selectPage(map, splitPageBean);
        if (appDynamics.size() == 0) return this.sucessJSON(new ArrayList<>(), "成功");
        ArrayList<DynamicDto> list = new ArrayList<>();
        appDynamics.forEach(e -> {
            //处理图片
            DynamicDto dd = new DynamicDto();
            BeanUtils.copyProperties(e, dd);
            if (!isNull(dd.getImage())) { //判断动态图片是否为空
                String[] arr = dd.getImage().split(","); //不为空  切割
                if (arr != null && arr.length > 0) {
                    dd.setImageList(Arrays.asList(arr)); //移入数组
                }
            } else {
                dd.setImageList(Arrays.asList());//为空  数组则为空
            }
            //是否点赞
            AppDynamicDianzan specifiedLike = appDynamicDianzanService.getSpecifiedLike(dd.getUserid(), dd.getId());
            dd.setDzstate(Objects.isNull(specifiedLike) ? 2 : 1);
            //点赞数量
            dd.setGivenum(appDynamicDianzanService.count(dd.getId()).size());
            //评论数量
            dd.setCommentnum(appCommentService.plcount(dd.getId()));
            //贵族设置
            AppUser user = appUserService.get(dd.getUserid());
            if (user.getIsguizu() == 1) {
                //根据贵族id  获取贵族图标
                String medal = guizuCacheMap.get(user.getNobleid());
                dd.setMedal(medal);
            } else {
                dd.setMedal("");
            }
            //头饰
            AppUserDressup dressup = appUserDressupService.getUserid(dd.getUserid(), 2);
            if (Objects.nonNull(dressup)) {
                //存在则放入
                dd.setToushi(Constants.toushiCacheMap.get(dressup.getMountsid()));
            } else {
                //不存在则表示未点赞
                dd.setToushi("");
            }
            if (redisUtil.hasKey(RedisKeys.BECKONING + userId + "-" + e.getUserid())) {
                dd.setIsBeckoning(1);
            } else {
                dd.setIsBeckoning(2);
            }
            dd.setTengxuncode(user.getTengxuncode());
            //显示发布时间
            dd.setFabuTime(format(dd.getCreatetime()));
            if (appUserService.isVip(user.getId())) {
                dd.setIsVip(1);
            }
            list.add(dd);
        });
        return this.sucessPage(list, splitPageBean.getNextPageNo());
    }

    /**
     * 获取动态通知角标
     *
     * @return
     */
    @RequestMapping("/dynamicBadge")
    @ResponseBody
    public Result dynamicBadge() {
        Map<String, Object> params = new HashMap<>();
        Integer userId = getUserId();

        if (redisUtil.hasKey(String.format(RedisKeys.USER_BADGE, userId))) {
            params.put("badge", true);
        } else {
            params.put("badge", false);
        }
        return sucessJSON(params);
    }

    /**
     * 动态通知
     *
     * @param pageno
     * @return
     */
    @RequestMapping("/dynamicAlert")
    @ResponseBody
    public Result dynamicAlert(Integer pageno) {
        Integer userId = getUserId();
        redisUtil.del(String.format(RedisKeys.USER_BADGE, userId));

        SplitPageBean splitPageBean = new SplitPageBean(pageno, 10);
        List<DynamicAlert> page = dynamicAlertService.page(userId, splitPageBean);
        return this.sucessPage(page, splitPageBean.getNextPageNo());
    }

    public static Integer oppositeSex(Integer sex) {
        if (sex == 2) {
            return 1;
        } else {
            return 2;
        }
    }
}
